package hello;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;
import auction.chapter08.UserCustomizeLoadSQL;

public class HelloWorldCustomSQL
{
	public static void main(String[] args)throws Exception{
		//test1();
		exeNamedQuery();
	}
	
	public static void exeNamedQuery()throws Exception{
		
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();
		
		UserCustomizeLoadSQL u=new UserCustomizeLoadSQL();
		u.setName("wei wei");
		s.save(u);

		tx.commit();
		s.close();
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		//if <sql-query> inside <class>, code need add package name
		Query q=s1.getNamedQuery("auction.chapter08.UserCustomizeLoadSQL.loadUser");
		// if <sql-query> at the same level as <class> use name directly
		//Query q=s1.getNamedQuery("loadUser");
		q.setParameter(0, 1L);//numbered from 0.
		List<UserCustomizeLoadSQL> r= q.list();
		out(r.get(0).getName());
		
		tx1.commit();
		s1.close();
	}
	
	public static void test1()throws Exception{
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();
		
		UserCustomizeLoadSQL u=new UserCustomizeLoadSQL();
		u.setName("wei wei");
		//s.save(u);

		tx.commit();
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		tx1.commit();
		s1.close();
		
		
		
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
	}
	
	public static void getParent(Class clazz)
	{
		Class parent=clazz.getSuperclass();
	  if(parent !=null)
	  {
			System.out.println("###"+parent.getName());
			getParent(parent);
		}
	}
	
	static void out(Object obj)
	{
		System.out.println("--->"+obj);
	}
}
